// 小程序 用户管理

var express = require('express');
var router = express.Router();
const db = require('../../db/db');


// 登录接口
router.post('/login', function (req, res, next) { 
  const { username, password } = req.body;

  console.log(username, password)
  
  
  if (!username || !password ) { // 检查验证码是否也为空

   return res.cc(0, "用户名、密码或验证码不能为空");
   
  }
    const sql = `select * from sys_systemset where F_AdminAccount = ?`;
  db.query(sql,  username, (err, result) => { 
    if (err) {

      return res.cc(0, '登录失败');
    } 
    if (result.length !== 1) {

      return res.cc(0, '登录失败');
    }
    if (result[0].F_AdminPassword !== password) {

      return res.cc(0, '账号或密码错误');
    }
       
        const data = {id:result[0].F_CreatorUserId }

    res.cc(200, '登录成功', data)

   })
});

// 查询个人信息
router.get('/userinfo', function (req, res, next) { 

  const { id } = req.query;
  const sql = `select * from sys_user where F_Id = ?`;
  db.query(sql, id, (err, result) => { 
    if (err) return res.cc(0, '查询失败');
    if (result.length !== 1) return res.cc(0, '查询失败');
    const userData = {
      username: result[0].F_Account,
      name: result[0].F_ReaName,
      gender: result[0].F_Gender,
      age: result[0].F_Birthday,
      phone: result[0].F_MobilePhone,
      email: result[0].F_Email,
      description: result[0].F_Description
    }
    res.cc(200, '查询成功', userData)
  })

})



// 修改个人信息
router.post('/updateInfo', function (req, res, next) {
 const { id } = req.body;
  const sql = `update sys_user set F_Account = ?, F_RealName = ?, F_Gender = ?, F_Birthday = ?, F_MobilePhone = ?, F_Email = ?, F_Description = ?,F_HeadImgUrl = ? where F_Id = ?`;
  db.query(sql, [req.body.username, req.body.name, req.body.gender, req.body.age, req.body.phone, req.body.email, req.body.description, id], (err, result) => {
    if (err) return res.cc(0, err);
    if (result.affectedRows !== 1) return res.cc(0, '修改失败');
    res.cc(200, '修改成功')
  })
})







module.exports = router;